import store, { type IModal } from "@/store";

/**
 *
 * @param func 回调函数
 * @param wait 延迟时间
 * @param immediate 是否立即执行
 * @returns
 */

export const debounce = (func: Function, wait = 1000, immediate = true) => {
  let args: any[];
  let context: any;
  let timer: number | null | undefined;

  const later = () =>
    setTimeout(() => {
      timer = null;
      if (!immediate) {
        func.apply(context, args);
        context = args;
      }
    }, wait);

  return function (this: any, ...params: any[]) {
    if (!timer) {
      timer = later();
      if (immediate) {
        func.apply(this, params);
      } else {
        context = this;
        args = params;
      }
    } else {
      clearTimeout(timer);
      timer = later();
    }
  };
};

/**
 *
 * @returns 根字体大小
 */

export const rootFontSize = () => {
  const appInstance = getApp() as any;

  let fontsize = appInstance.globalData?.fontsize;
  if (fontsize) {
    return fontsize;
  }

  let minSize = Math.min(uni.getWindowInfo().windowWidth, uni.getWindowInfo().windowHeight);
  let size = Math.max(Math.min(600, minSize), 180);
  fontsize = size / 37.5;
  appInstance.globalData.fontsize = fontsize;

  return fontsize;
};

/**
 * 根据区间替换字符
 * @param str
 * @param startIndex
 * @param endIndex
 * @param newChar
 */
export const replaceChar = (str: string, startIndex: number, endIndex: number, newChar: any) => {
  if (startIndex < 0 || startIndex >= str.length || endIndex < 0 || endIndex >= str.length) {
    return str; // 如果索引超出范围，则直接返回原字符串
  }
  return str.substring(0, startIndex) + newChar + str.substring(endIndex);
}

/**
 * 根据状态值获取数组对应的键值对数据
 * @param status 状态值
 * @param arr 对应数组
 * @param key
 */
export const getStatus = <T, K extends keyof T>(status: any, arr: T[], key?: K) => {
  let data: T | { desc: string, code: number, className: string };
  let not_data = {
    desc: '-',
    code: -1,
    className: ''
  }
  if (arr && arr.length) {
    let field: any = key ? key : 'code';
    let index: number = arr.findIndex((item: any) => item[field] == status);
    !~index ? (data = not_data) : (data = arr[index]);
  } else {
    data = not_data;
  }
  return data
}

/**
 * 格式化数字单位
 * @param num
 */
export const formatNumber = (num: number | string) => {
  let _num = Number(num);
  if (isNaN(_num)) return num;
  if (_num >= 1000 && _num < 10000) {
    return Number((_num / 1000).toFixed(2)) + 'K';
  } else if (_num >= 10000) {
    return Number((_num / 10000).toFixed(2)) + 'W';
  } else {
    return _num.toString();
  }
}

/**
 * 根据字母排序
 * @param list 排序的数组
 * @param field 排序的字段
 */
export const sortLetter = (list: any[] = [], field: string) => {
  function fun(a: any, b: any) {
    const f = a[field].toUpperCase();
    const l = b[field].toUpperCase();
    if (f < l) {
      return -1;
    }
    if (f > l) {
      return 1;
    }
    return 0;
  }
  return list.sort(fun);
}

/**
 * 格式化时间为00*00格式
 * @param seconds 秒数
 * @param format 格式
 * @param separator 分隔符
 * @param isNotReturnEmpty 当各项值为0时是否返回 false 为返回 true 为不反悔
 */
export const getFormatTime = (seconds: number, format: 'hh-mm-ss' | 'mm-ss', separator: string = ':-:', isNotReturnEmpty: boolean = false) => {
  const timeData: any = {
    'ss': parseInt((Number(seconds) % 60) as any),
    'mm': parseInt((Number(seconds) / 60 % 60) as any),
    'hh': parseInt((Number(seconds) / 60 / 60 % 24) as any)
  }
  let time: any = null;
  let format_list: string[] = format.split('-');
  for (let i: number = 0; i < format_list.length; i++) {
    if (isNotReturnEmpty && !timeData[format_list[i]]) continue;
    if (!time) time = `${timeData[format_list[i]].toString().padStart(2, '0')}`
    else time += `${separator.split('-')[i - 1]}${timeData[format_list[i]].toString().padStart(2, '0')}`;
  }
  return time;
}

export class util {
  static dialogueTimer: number = -1;
  static dialogueCallback: Function | null;
  static showLoading() {
    store.dispatch("setLoadingAction", true);
  }

  static hideLoading() {
    store.dispatch("setLoadingAction", false);
  }

  static showDialogue(msg: string, showTime: number = 2000, dialogueCallback?: Function) {
    if (this.dialogueTimer !== -1) {
      clearTimeout(this.dialogueTimer);
      this.dialogueTimer = -1;
      this.dialogueCallback = null;
    }
    store.dispatch("setDialogueMsg", msg);
    store.dispatch("setDialogueIsShow", true);
    dialogueCallback && (this.dialogueCallback = dialogueCallback);
    this.dialogueTimer = setTimeout(() => {
      this.dialogueCallback && this.dialogueCallback();
      store.dispatch("setDialogueIsShow", false);
    }, showTime)
  }

  static showModal(params: IModal) {
    const { title, isShowModal = true, cancelBtnText = "取消", confirmBtnText = "确认", success = () => { }, cancel = () => { } } = params;

    store.dispatch("setModalIsShow", {
      title,
      isShowModal,
      cancelBtnText,
      confirmBtnText,
      success,
      cancel,
    })
  }
}



